from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from home.homeser import NavSerializer, BannerSerializer
from home.models import Nav, Banner
from django.core.cache import cache


class Header(APIView):
    def get(self,request):
        nav = Nav.objects.filter(position=1,isdel=0).order_by('sort')
        ser = NavSerializer(nav,many=True)
        return Response({
            "code":200,
            "msg":"success",
            "data":ser.data
        })


class Footer(APIView):
    def get(self,request):
        nav = Nav.objects.filter(position=0,isdel=0).order_by('sort')
        ser = NavSerializer(nav,many=True)
        return Response({
            "code":200,
            "msg":"success",
            "data":ser.data
        })


class BannerView(APIView):
    def get(self,request):
        # 缓存中有数据先读缓存，没有数据查数据库 写缓存 再返回数据
        bannerdata = cache.get('banner')
        if bannerdata:
            return Response({"msg":"ok","code":200,"data":bannerdata})
        # 获取头部数据
        banner = Banner.objects.filter(isdel=0).order_by('sort')
        # banner = Banner.objects.filter(isdel=0).order_by('sort')
        ser = BannerSerializer(banner,many=True)
        cache.set('banner',ser.data,3600)
        return Response({
            "code":200,
            "msg":"success",
            "data":ser.data
        })
